<template>
  <div style="float: left;margin-top: 5px">
    <el-form ref="dicSearchRef" :model="searchFormData">
      <el-form-item label="分组名称" >
        <el-input v-model="searchFormData.groupName" type="text"></el-input>
      </el-form-item>
    </el-form>
  </div>
  <div style="height: 40px;margin-top: 5px;float: left;margin-left: 20px;">
    <el-button @click="searchDicClick">查询</el-button>
    <el-button @click="resetSearchClick">重置</el-button>
    <el-button v-check-permission="'system:dic:add'" @click="addDicClick">新增</el-button>
  </div>
  <div style="clear: both"></div>
  <div style="height: calc(100% - 60px);">
    <div style="width: 200px;float: left;height: 100%;overflow: auto">
      <Tree ref="leftGroupTree" :tree-data="groupTreeData"  :show-check-box="false" :options="groupTreeOptions"
            :data-config="groupTreeConfig" :node-click="dicGroupTreeNodeClick" :expanded-model="ExpandedModel.SINGLE">
      </Tree>
    </div>
    <div style="width: calc(100% - 200px);float: left;height: 100%">
      <Table  :show-page="true" ref="tableRef" :show-line-number="true"
              :showCheckBox="false" :url="dicGridUrl" :columns="columns">
        <template  v-slot:handle="slotProps">
          <el-button v-check-permission="'system:dic:update'" @click.stop="editTableData(slotProps.rowData,slotProps.rowIndex)">编辑</el-button>
          <el-button v-check-permission="'system:dic:delete'" @click.stop="deleteTableRowData(slotProps.rowData,slotProps.rowIndex)">删除</el-button>
        </template>
      </Table>
    </div>
    <div style="clear: both"></div>
  </div>

  <DialogForm ref="dicEditFormRef" :form="dicForm" title="编辑字典表" @validateSuccess="validateSuccess">
    <template v-slot:dicTree="slotProps">
      <Tree ref="selectTree" :tree-data="dicTreeData" :checked-model="CheckedModel.SINGLE" :options="groupTreeOptions"
            :data-config="groupTreeConfig" :checked-change="checkedChange">
      </Tree>
    </template>
  </DialogForm>
</template>

<style scoped>

</style>
<script setup >

import Table from "@/components/plugs/table/Table.vue";
import Tree from "@/components/plugs/tree/Tree.vue"
import {inject, reactive, ref, toRaw} from "vue";
import DialogForm from "@/components/plugs/form/DialogForm.vue";
import {FormItemType} from "@/components/plugs/form/DialogFormInterface.js";
import {AXIOS_NAME,TOKEN_NAME_KEY,TOKEN_VALUE_KEY} from '@/constant/constant.js';
import {ElMessage} from "element-plus";
import {deleteRow, HandleEnum} from "@/utils/utils.ts";
import {CheckedModel, ExpandedModel} from "@/components/plugs/tree/TreeView.js";

let groupTreeData = reactive([]);
const leftGroupTree = ref(null);
const $axios = inject(AXIOS_NAME);
const selectTree = ref(null);
const dicTreeData = reactive([]);
const dicGridUrl = ref("/dictionary/getDicList");
const dicEditFormRef = ref(null);
const tableRef = ref(null);
const searchFormData = reactive({groupName: ''});
const dicSearchRef = ref(null);

/***
 enable:true,
 idKey:"id",
 pIdKey:"pId",
 */

const menuTreeOptions = {
  "label": 'groupName'
}

const groupTreeOptions = {
  "label": 'text'
}
const dataConfig = {
  simple: true,
  pFiled:'pId',
  idField: 'groupId',
  rootId: '0'
};
const groupTreeConfig  = {
  simple: true,
  pFiled:'pId',
  idField: 'id',
  rootId: '0'
}
//列表
const columns = ref([
  {field:"groupId","desc": "分组标识"},
  {field:"groupName","desc": "分组名称"},
  {field:"text","desc": "显示名称"},
  {field:"val","desc": "值"},
  {field:"orderNum","desc": "排序"},
  {field:"showTime","desc": "创建时间",width: 200},
  {field:"handle","desc": "操作",width:150,isSlot: true,fixed: 'right'}
]);


//表单
let items = [];
items.push({type: FormItemType.INPUT_HIDDEN,label: 'id',name: 'id'});
items.push({type: FormItemType.CUSTOMIZE_SELECT,label: '已分组标识',name: 'temp',
  url: '/dictionary/getDicType',textFiled:'groupName',valueField: "groupId",selectedChange:function (selected){
    dicEditFormRef.value.setData({
      "groupName":selected.groupName,
      "groupId":selected.groupId
    });
    selectTree.value.setCheckedKeys([selected.pId]);
}});
items.push({type: FormItemType.INPUT_TEXT,label: '分组标识',name: 'groupId',placeholder: '请填写分组标识'});
items.push({type: FormItemType.INPUT_TEXT,label: '分组名称',name: 'groupName',placeholder: '请填写分组名称'});
items.push({type: FormItemType.INPUT_TEXT,label: '显示名称',name: 'text',placeholder: '请填写显示名称'});
items.push({type: FormItemType.INPUT_TEXT,label: '值',name: 'val',placeholder: '请填写值'});
items.push({type: FormItemType.INPUT_NUMBER,label: '排序',name: 'orderNum',placeholder: '请填写排序'});
items.push({type: FormItemType.SLOT,label: '父级',name: 'dicTree'});
let dicForm = reactive({
  splitCol: 1,
  gutter: 20,
  items:items,
  rules:{
    groupId: [
      { required: true, message: '请填写分组标识', trigger: 'blur' }
    ],
    groupName: [
      { required: true, message: '请填写分组名称', trigger: 'blur' }
    ],
    text: [
      { required: true, message: '请填写显示名称', trigger: 'blur' }
    ],
    val: [
      { required: true, message: '请填写值', trigger: 'blur' }
    ],
    orderNum: [
      { required: true, message: '请填写排序', trigger: 'blur' }
    ]
  },
});

async function validateSuccess(data){
  let url = '/dictionary/insertDic';
  if(data.id != null ){
    url = '/dictionary/updateDic'
  }
  let arr = selectTree.value.getCheckedKeys();
  if(arr != null && arr.length > 0){
    if(arr[0] == data.groupId){
      ElMessage.error("不能选择同节点为父节点!");
      return;
    }
    data.pId = arr[0];
  }else {
    data.pId = '0';
  }
  const result=  await $axios.post('/dictionary/isDataExsit',data);
  if(result.data.code == -1){
    ElMessage.error(result.data.msg);
    return;
  }
  $axios.post(url,data).then( respone=> {
    const data = respone.data;
    if(data.code == -1){
      ElMessage.error("保存字典数据失败!");
      return;
    }
    ElMessage.info("保存典数据成功!");
    dicEditFormRef.value.close();
    tableRef.value.reload();
    getDicGroupTreeData();
  }).catch(error => {

  });
}


const addDicClick = () =>{
  dicEditFormRef.value.show();
  dicEditFormRef.value.restForm();
  getMenuTreeData();
}

const editTableData = (data,rowIndex) => {
  dicEditFormRef.value.show();
  dicEditFormRef.value.setData(data);
  getMenuTreeData();
}

const deleteTableRowData = (data,rowIndex) => {
  deleteRow("/dictionary/deleteDic",data,function (state,data){
    if(state == HandleEnum.SUCCESS){
      tableRef.value.reload();
    }
  });
}

const searchDicClick = () =>{
  const data = toRaw(searchFormData);
  tableRef.value.reload(data);
}

const resetSearchClick = () => {
  searchFormData.groupName = '';
}

const getMenuTreeData = () =>{
  dicTreeData.clear();
  $axios.post('/dictionary/getTreeDicData',{}).then(response => {
      const data = response.data;
      if(data.code == 1){
        for(const item of data.data){
          item.pId = (item.pId == null || item.pId == '') ? '0' : item.pId;
          dicTreeData.push(item);
        }
      }
  },error =>{

  });
}

const getDicGroupTreeData = () =>{
  groupTreeData.clear();
  $axios.post("/dictionary/getTreeDicData",{}).then(response => {
    const data = response.data;
    if(data.code == 1){
      groupTreeData.pushAll(data.data);
    }
  },error => {

  })
}
getDicGroupTreeData();
const checkedChange = (node,checked,allCheckedData) =>{
  if(!node.pNode){
     let arr = selectTree.value.getCheckedKeys();
     selectTree.value.setCheckedKeys([]);
  }
}
const dicGroupTreeNodeClick = (data,_node) => {
  if(!data.children){
    return
  }
  tableRef.value.reload({"groupName": data.text});
}
</script>
